﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Syspetro.Core.Extensions;
using System;
using System.Linq;
using System.Reflection;

namespace Syspetro.Core.DynamicApi
{
    /// <summary>
    /// Register Controller Routing Information Converter
    /// </summary>
    public class DynamicApiConvention : IApplicationModelConvention
    {

        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                var type = controller.ControllerType.AsType();
                var dynamicWebApiAttr = AttributeHelper.GetSingleAttributeOrDefaultByFullSearch<DynamicApiAttribute>(type.GetTypeInfo());
                if (typeof(IDynamicApi).GetTypeInfo().IsAssignableFrom(type))
                {
                    controller.ControllerName = controller.ControllerName.RemovePostFix(AppConsts.ControllerPostfixes.ToArray());
                    ConfigureDynamicWebApi(controller, dynamicWebApiAttr);
                }
                else
                {
                    if (dynamicWebApiAttr != null)
                    {
                        ConfigureDynamicWebApi(controller, dynamicWebApiAttr);
                    }
                }

            }
        }

        private static void ConfigureArea(ControllerModel controller, DynamicApiAttribute attr)
        {
            if (!controller.RouteValues.ContainsKey("area"))
            {
                if (!string.IsNullOrEmpty(attr?.Area))
                {
                    controller.RouteValues["area"] = attr.Area;
                }
                else if (!string.IsNullOrEmpty(AppConsts.DefaultAreaName))
                {
                    controller.RouteValues["area"] = AppConsts.DefaultAreaName;
                }
            }
        }
        private static void ConfigureGroup(ControllerModel controller, DynamicApiAttribute attr)
        {
            if (controller.ApiExplorer.GroupName.IsNullOrEmpty())
            {
                if (attr != null)
                    controller.ApiExplorer.GroupName = attr.GroupName;
                else
                    controller.ApiExplorer.GroupName = AppConsts.DefaultGroupName;
            }
            DynamicApiGroups.AddGroupInfo(new GroupExtraInfo
            {
                Group = controller.ApiExplorer.GroupName,
                Version = attr?.Version ?? "V1",
                Title = attr?.Title
            });
        }
        private static void ConfigureControllerVisible(ControllerModel action, DynamicApiAttribute controllerAttr)
        {
            if (!action.ApiExplorer.IsVisible.HasValue)
                action.ApiExplorer.IsVisible = controllerAttr?.IgnoreApi ?? true;
        }

        private static void ConfigureDynamicWebApi(ControllerModel controller, DynamicApiAttribute controllerAttr)
        {
            ConfigureArea(controller, controllerAttr);
            ConfigureGroup(controller, controllerAttr);
            ConfigureControllerVisible(controller, controllerAttr);
            ConfigureSelector(controller, controllerAttr);
            ConfigureParameters(controller);
            DynamicApiGroups.ControllerTypes.Add(controller.ControllerType.AsType());
        }


        private static void ConfigureParameters(ControllerModel controller)
        {
            foreach (var action in controller.Actions)
            {
                foreach (var para in action.Parameters)
                {
                    if (para.BindingInfo != null)
                    {
                        continue;
                    }
                    if (!TypeHelper.IsPrimitiveExtendedIncludingNullable(para.ParameterInfo.ParameterType))
                    {
                        if (CanUseFormBodyBinding(action, para))
                        {
                            para.BindingInfo = BindingInfo.GetBindingInfo(new[] { new FromBodyAttribute() });
                        }
                    }
                }
            }
        }


        private static bool CanUseFormBodyBinding(ActionModel action, ParameterModel parameter)
        {
            if (AppConsts.FormBodyBindingIgnoredTypes.Any(t => t.IsAssignableFrom(parameter.ParameterInfo.ParameterType)))
            {
                return false;
            }

            foreach (var selector in action.Selectors)
            {
                if (selector.ActionConstraints == null)
                {
                    continue;
                }

                foreach (var actionConstraint in selector.ActionConstraints)
                {

                    if (actionConstraint == null)
                    {
                        continue;
                    }

                    if ((actionConstraint as HttpMethodActionConstraint).HttpMethods.All(hm => hm.IsIn(false,"GET", "DELETE", "TRACE", "HEAD")))
                    {
                        return false;
                    }
                }
            }

            return true;
        }


        #region ConfigureApiExplorer

        private static void ConfigureApiExplorer(ActionModel action)
        {
            DynamicApiGroups.ActionTypes.Add(action.ActionMethod);
            if (!action.ApiExplorer.IsVisible.HasValue)
            {
                var nonAttr = AttributeHelper.GetSingleAttributeOrDefault<DynamicApiAttribute>(action.ActionMethod);
                action.ApiExplorer.IsVisible = nonAttr?.IgnoreApi ?? true;
            }
        }

        #endregion

        private static void ConfigureSelector(ControllerModel controller, DynamicApiAttribute controllerAttr)
        {
            if (controller.Selectors.Any(selector => selector.AttributeRouteModel != null))
            {
                foreach (var action in controller.Actions)
                {
                    ConfigureApiExplorer(action);
                }
            }
            else
            {
                var areaName = string.Empty;
                if (controllerAttr != null)
                {
                    areaName = controllerAttr.Area;
                }
                foreach (var action in controller.Actions)
                {
                    ConfigureSelector(areaName, controller.ControllerName, action);
                    ConfigureApiExplorer(action);
                }
            }
        }

        private static void ConfigureSelector(string areaName, string controllerName, ActionModel action)
        {

            var nonAttr = AttributeHelper.GetSingleAttributeOrDefault<NonDynamicApiAttribute>(action.ActionMethod);

            if (nonAttr != null)
            {
                return;
            }

            if (action.Selectors.IsNullOrEmpty() || action.Selectors.Any(a => a.ActionConstraints.IsNullOrEmpty()))
            {
                AddAppServiceSelector(areaName, controllerName, action);
            }
            else
            {
                NormalizeSelectorRoutes(areaName, controllerName, action);
            }
        }

        private static void AddAppServiceSelector(string areaName, string controllerName, ActionModel action)
        {

            var verb = GetHttpVerb(action);

            action.ActionName = GetRestFulActionName(action.ActionName);

            var appServiceSelectorModel = action.Selectors[0];

            if (appServiceSelectorModel.AttributeRouteModel == null)
            {
                appServiceSelectorModel.AttributeRouteModel = CreateActionRouteModel(areaName, controllerName, action);
            }

            if (!appServiceSelectorModel.ActionConstraints.Any())
            {
                appServiceSelectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new[] { verb }));
                switch (verb)
                {
                    case "GET":
                        appServiceSelectorModel.EndpointMetadata.Add(new HttpGetAttribute());
                        break;
                    case "POST":
                        appServiceSelectorModel.EndpointMetadata.Add(new HttpPostAttribute());
                        break;
                    case "PUT":
                        appServiceSelectorModel.EndpointMetadata.Add(new HttpPutAttribute());
                        break;
                    case "DELETE":
                        appServiceSelectorModel.EndpointMetadata.Add(new HttpDeleteAttribute());
                        break;
                    default:
                        throw new Exception($"Unsupported http verb: {verb}.");
                }
            }


        }



        /// <summary>
        /// Processing action name
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="RemovePrefix"></param>
        /// <returns></returns>
        private static string GetRestFulActionName(string actionName,bool RemovePrefix = false)
        {
            // custom process action name
            var appConstsActionName = AppConsts.GetRestFulActionName?.Invoke(actionName);
            if (appConstsActionName != null)
            {
                return appConstsActionName;
            }

            // default process action name.

            // Remove Postfix
            actionName = actionName.RemovePostFix(AppConsts.ActionPostfixes.ToArray());

            // Remove Prefix
            if(RemovePrefix)
            {
                var verbKey = actionName.GetPascalOrCamelCaseFirstWord().ToLower();
                if (AppConsts.HttpVerbs.ContainsKey(verbKey))
                {
                    if (actionName.Length == verbKey.Length)
                    {
                        return "";
                    }
                    else
                    {
                        return actionName[verbKey.Length..];
                    }
                }
            }
            return actionName;
        }

        private static void NormalizeSelectorRoutes(string areaName, string controllerName, ActionModel action)
        {
            action.ActionName = GetRestFulActionName(action.ActionName);
            foreach (var selector in action.Selectors)
            {
                selector.AttributeRouteModel = selector.AttributeRouteModel == null ?
                     CreateActionRouteModel(areaName, controllerName, action) :
                     AttributeRouteModel.CombineAttributeRouteModel(CreateActionRouteModel(areaName, controllerName, action), selector.AttributeRouteModel);
            }
        }

        private static string GetHttpVerb(ActionModel action)
        {
            var getValueSuccess = AppConsts.AssemblyDynamicApiOptions
                .TryGetValue(action.Controller.ControllerType.Assembly, out AssemblyDynamicApiOptions assemblyDynamicWebApiOptions);
            if (getValueSuccess && !string.IsNullOrWhiteSpace(assemblyDynamicWebApiOptions?.HttpVerb))
            {
                return assemblyDynamicWebApiOptions.HttpVerb;
            }


            var verbKey = action.ActionName.GetPascalOrCamelCaseFirstWord().ToLower();

            var verb = AppConsts.HttpVerbs.ContainsKey(verbKey) ? AppConsts.HttpVerbs[verbKey] : AppConsts.DefaultHttpVerb;
            return verb;
        }

        private static string GetApiPreFix(ActionModel action)
        {
            var getValueSuccess = AppConsts.AssemblyDynamicApiOptions
                .TryGetValue(action.Controller.ControllerType.Assembly, out AssemblyDynamicApiOptions assemblyDynamicWebApiOptions);
            if (getValueSuccess && !string.IsNullOrWhiteSpace(assemblyDynamicWebApiOptions?.ApiPrefix))
            {
                return assemblyDynamicWebApiOptions.ApiPrefix;
            }

            return AppConsts.DefaultApiPreFix;
        }

        private static AttributeRouteModel CreateActionRouteModel(string areaName, string controllerName, ActionModel action)
        {
            var apiPreFix = GetApiPreFix(action);
            var routeStr = $"{apiPreFix}/{areaName}/{controllerName}/{action.ActionName}".Replace("//", "/");
            return new AttributeRouteModel(new RouteAttribute(routeStr));
        }
    }
}
